// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Dogs attack script
// -----------------------------------------------

private [
	"_cible",
	"_group",
	"_position",
	"_recheck",
	"_unit",
	"_oldgroup"
];

_unit = _this select 0;

_oldgroup = group _unit;

_position = [0,0,0];
_unit setVariable ["destination", _position, false];

WC_fnc_definedogcible = {
	private ["_dog","_cible","_cibles","_list","_oldgroup"];

	_dog      = _this select 0;
	_oldgroup = _this select 1;

	_cibles = [];
	_list = (position _dog) nearEntities ["CAManBase", 50];
	if (count _list > 0) then {
		{
			if (isPlayer _x) then {
				_cibles = _cibles + [_x];
			} else {
				_list = _list - [_x];
			};
			sleep 0.1;
		} foreach _list;
	} else {
		_cibles = [];
	};

	if (count _cibles == 0) then {
		_cible = objNull;
	} else {
		_cible = (([_dog, _cibles] call EXT_fnc_SortByDistance) select 0);
		// Master of dogs discover cibles
		_oldgroup setBehaviour "COMBAT";
		_oldgroup reveal _cible;
	};
	_cible;
};

_cible = objNull;
_recheck = 0;

while {alive _unit} do {
	if (isNull _cible or !alive _cible or _cible distance _unit > 100) then {
		_cible = [_unit] call WC_fnc_definedogcible;
	};

	// If no cible
	if (isNull _cible) then {
		if ((count units _oldgroup > 0) and (group _unit != _oldgroup)) then {
			[_unit] joinSilent _oldgroup;
		};
	} else {
		if (group _unit == _oldgroup) then {
			_group = createGroup east;
			[_unit] joinSilent _group;
		};
		if (_unit distance _cible > 3) then {
			_position = position _cible;
			_unit setVariable ["destination", _position, false];
			_unit setSpeedMode "full";
			_unit setBehaviour "safe";
			_unit doMove _position;
			if (random 1 > 0.9) then {
				wcdoggrognement = true;
				["wcdoggrognement", "client", owner _cible] call WC_fnc_publicvariable;
			};
		} else {
			_unit doWatch _cible;
			wcdogbark = true;
			["wcdogbark", "client", owner _cible] call WC_fnc_publicvariable;
			_cible setDamage ((damage _cible) + 0.05);
			sleep ceil(random 3);
		};
		_recheck = _recheck + 1;
		if (_recheck > 3) then {
			_cible = [_unit] call WC_fnc_definedogcible;
			_recheck = 0;
		};
	};
	sleep 1;
};